package ooday04;

public class PolymorphicDemo {
    public static void main(String[] args) {

       //演示向上类型
       /* Dog o1 = new Dog("小黑", 2, "黑");//狗是狗
        //o1.name/age/color/drink()/eat()/swim()/lookHome();
        Animal o2 = new Dog("小黑", 2, "黑");//狗是动物---向上造型
        //o2.name/age/color/drink()/eat() 只能访问animal父类的
        Swim o3 = new Dog("小黑", 2, "黑"); //狗会游泳---向上造型
        //只能访问父类 接口的o3.swim()*/

      /*  Master master = new Master();
        Animal dog = new Dog("小黑", 2, "黑");
        Animal chick = new Chick("小花", 3, "花");
        Animal fish = new Fish("小金", 1, "金");
       //Dog dog =new Dog("小黑",2,"黑");
        Chick chick=new Chick("小花",3,"花");
        Fish fish=new Fish("小金",1,"金");
        master.feed(dog);//Animal animal=dog 在传参的同时，系统自动做了向上造型
        master.feed(chick);
        master.feed(fish);
*/

        //Animal o=new Animal()//编译错误，animal是抽象类，抽象类不能被实例化
        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小黑", 2, "黑");
        animals[1] = new Dog("小白", 1, "白");
        animals[2] = new Dog("小金", 2, "金");
        animals[3] = new Chick("小花", 3, "花");
        animals[4] = new Fish("小金", 1, "金");
        for (int i = 0; i < animals.length; i++) {//遍历所有动物
            System.out.println(animals[i].name);//输出每个动物的名字
            animals[i].drink();
            animals[i].eat();
            //只能访问父类animal的方法
            if (animals[i] instanceof Dog){
                Dog dog =(Dog) animals[i];
                dog.lookHome();

            }
            if (animals[i] instanceof Chick){
                Chick chick=(Chick) animals[i];
                chick.LayEggs();
            }
            if (animals[i] instanceof Fish){
                Fish fish =(Fish) animals[i];
            }
            if (animals[i] instanceof Swim){//适用于所有实现Swim接口的(会游泳的)
                Swim swim=(Swim) animals[i];
            }
        }

        //向下转型
        /*Animal o=new Dog("小黑",2,"黑");
        Dog g=(Dog) o;//引用o所指向的对象，就是Dog类型
        Swim s=(Swim) o;//引用o所指向的对象，实现了Swim接口
        //Fish f =(Fish) o;//运行时会发生classCastException类型转换异常
        if (o instanceof Fish){//false
            Fish f =(Fish) o;
        }
        System.out.println(o instanceof Fish);
        System.out.println(o instanceof Dog);
        System.out.println(o instanceof Swim);*/
    }
}
